package find.prj.lib;

import java.io.File;

public class FileSearch implements Runnable {
	
	private String SearchKeyWord;
	private File RootPath;
	private String ExcludeKeyWord;
	
	private FileNamesStringArray FilteredFileNames;
	private FileNamesStringArray ExcludedFileNames;
	
	public FileSearch() {
	}

	public FileSearch(String searchKeyWord, String rootPath, String excludeKeyWord) {
		this.setSearchKeyWord(searchKeyWord);
		this.setRootPath(rootPath);
		this.setExcludeKeyWord(excludeKeyWord);
	}

	public void setSearchKeyWord (String searchKeyWord) {
		this.SearchKeyWord = searchKeyWord;
	}
	
	public void setExcludeKeyWord (String excludeKeyWord) {
		this.ExcludeKeyWord = excludeKeyWord;
	}

	public void setRootPath (String rootPath) {
		this.RootPath = new File(rootPath);
	}
	
	public FileNamesStringArray getFilteredFileNames() {
		return this.FilteredFileNames; 
	}
	
	public FileNamesStringArray getExcludedFileNames() {
		return this.ExcludedFileNames;
	}
		
	private FileNamesStringArray filterFileNamesRecursive (File rootPath) {
		FileNamesStringArray filteredFileNames = new FileNamesStringArray();
		File[] listOfFiles = rootPath.listFiles();
		if (listOfFiles == null)
			return filteredFileNames;
		for(File file : listOfFiles) { 
			if (file.isFile())
				if (file.getName().toLowerCase().contains(this.SearchKeyWord.toLowerCase())) {
					filteredFileNames.add(file.getPath());
				}
			
			if(file.isDirectory())
				filteredFileNames.addAll(this.filterFileNamesRecursive(file));
			}
		return filteredFileNames;
	}
	
	public void filterFileNames () {
		this.FilteredFileNames = this.filterFileNamesRecursive(this.RootPath);
	}
	
	public void excludeFileNames() {
		FileNamesStringArray fileNames = (FileNamesStringArray) this.FilteredFileNames.clone();		//casting to (FileNamesStringArray)
		for (int i=0; i < fileNames.size(); ) {
			String[] s = fileNames.get(i).toLowerCase().split("\\\\");
			if (s[s.length-1].contains(this.ExcludeKeyWord.toLowerCase()))
				fileNames.remove(fileNames.get(i));
			else
				i++;
		}
		this.ExcludedFileNames = fileNames;
	}

	@Override
	public void run() {
		this.filterFileNames();
		this.excludeFileNames();
	}
	
}